package com.liuyucheng.concurrent.threadpool;

import cn.hutool.core.util.RandomUtil;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 线程池示例
 * @author LiuYuCheng
 * @date 2023年10月19日 09:32
 */
public class ThreadPoolDemo {

    public static void main(String[] args) throws Exception{
        testAwaitTermination();
    }

    /**
     * 等待线程池中所有任务执行完成的方法
     */
    public static void testAwaitTermination() throws Exception{
        // 等待线程池中所有任务执行完成的方法
        ExecutorService executorService = Executors.newFixedThreadPool(12);
        List<String> list = new CopyOnWriteArrayList<>();

        for (int i = 0; i < 100; i++) {
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    String name = String.valueOf(RandomUtil.randomInt());
                    list.add(name);
                    try {
                        Thread.sleep(500L);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println("name = " + name);
                }
            });
        }

        executorService.shutdown();
        boolean b = executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES);
        System.out.println("线程池执行完成");
        System.out.println("list.size() = " + list.size());
    }

}
